# !/usr/bin/env python
# coding=utf-8
# @Time    : 2017/12/20 15:17
# @Author  : 6imensiva
# @Site    : https://gitee.com/dimensiva/wx_server_prototype.git
# @File    : token_service.py
# @Software: PyCharm
# @Version: 3.5.4
from app.dao import my_redis
from utils import my_request, my_exception
from configs import current_config
from app.common import my_response


def get_server_access_token(refresh=False):
	"""
	获取后台服务器的access token，先找redis，没有再找微信后台要

	:param refresh: 是否强制刷新token
	:return: my_response
	"""
	if refresh:
		token = _request_server_access_token()
	else:
		# token = _request_server_access_token()
		token = my_redis.get_data('server_access_token')
		if not token:
			token = _request_server_access_token()

	if token:
		return my_response.success(token)
	else:
		return my_response.fail('获取token失败')


def get_server_access_token2(refresh=False):
	"""
	获取后台服务器的access token，先找redis，没有再找微信后台要

	:param refresh: 是否强制刷新token
	:return: token
	"""
	token = my_redis.get_data('server_access_token')
	if refresh or not token:
		url = current_config.SERVER_ACCESS_TOKEN_URL % (current_config.APPID,
		                                                current_config.APPSECRET)
		ret_dict = my_request.my_request4('GET', url, parse_format='json')
		if ret_dict.get('errcode'):
			raise my_exception.MyException('fail to get access_token:'+ret_dict['errmsg'])
		my_redis.set_data('server_access_token', ret_dict['access_token'],
		                  ret_dict['expires_in'])
		token = ret_dict['access_token']
	return token


def _request_server_access_token():
	url = current_config.SERVER_ACCESS_TOKEN_URL % (current_config.APPID, current_config.APPSECRET)
	code, ret_dict = my_request.my_request4('GET', url, parse_format='json')
	if code != 200:
		return None

	my_redis.set_data('server_access_token', ret_dict['access_token'], ret_dict['expires_in'])
	return ret_dict['access_token']


def get_web_access_token(code):
	"""
	获取网页授权access_token,先从redis获取；失败再向微信申请

	:class ret_dict: {
		"access_token":"ACCESS_TOKEN",
		"expires_in":7200,
		"refresh_token":"REFRESH_TOKEN",
		"openid":"OPENID",
		"scope":"SCOPE",
		"errcode":40029,
		"errmsg":"invalid code"}
	:param code: 前端提供的申请凭证
	:return: my_response
	"""
	token = my_redis.get_data('web_access_token_' + code)
	if not token:
		url = current_config.WEB_ACCESS_TOKEN_URL % (current_config.APPID, current_config.APPSECRET, code)
		ret_dict = my_request.my_request5('GET', url, parse_format='json')
		if 'errmsg' in ret_dict:
			return my_response.fail(ret_dict['errmsg'])
		token = ret_dict['access_token']
		my_redis.set_data('web_access_token_' + code, token, ret_dict['expires_in'])
		# todo: handle refresh_token

	print(token)
	return my_response.success(ret_dict)